package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ndp.ec.core.ExecCommandService;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.exception.CheckedException;
import com.ndp.fb.mongo.api.EcTemplateCreateMongoService;
import com.ndp.fb.mongo.model.EcTemplateCreate;
import com.ndp.fb.rdb.api.EcTemplateMaterielRdbService;
import com.ndp.fb.rdb.model.EcMaterielTag;
import com.ndp.fb.rdb.model.EcTemplateMateriel;
import com.ndp.fb.rdb.model.EcTemplateMaterielExt;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.walle.business.EcService;
import com.ndp.fb.walle.business.EcTemplateMaterielService;
import com.ndp.fb.walle.model.bo.ecmaterieltag.EcMaterielTagResult;
import com.ndp.fb.model.business.vo.BaseVoParam;
import com.ndp.fb.walle.model.vo.JobParam;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.AdvancedParam;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.EcBuildCreativeParam;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.EcTempMateSaveParam;
import com.ndp.fb.walle.model.vo.ectemplatemateriel.param.EcTemplateMaterielParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hexin on 2016/5/18.
 */
@RestController
@RequestMapping("/ecTemplateMateriel")
public class EcTemplateMaterielController {


    @Autowired
    EcTemplateMaterielService ecTemplateMaterielService;

    @Autowired
    private EcService ecService;

    @Reference
    private EcTemplateCreateMongoService ecTemplateCreateMongoService;

    @RequestMapping("findByEditOrCopy")
    public Map findByEditOrCopy(@RequestParam(value = "param") String param, HttpServletRequest req) {
        JSONObject jsonObject = JSON.parseObject(param);
        Long id = jsonObject.getLong("id");
        User user = (User) req.getSession().getAttribute("user");
        return ecTemplateMaterielService.findByEditOrCopy(user.getLanguage(),id);
    }

    @RequestMapping("findByFeed")
    Collection<EcTemplateMateriel> findEcTemplateMaterielByFeed(@RequestParam Long feedId) {
        List<EcTemplateMateriel> allEcTemplate = ecService.findEcTemplateMaterielByFeedId(feedId);
        return allEcTemplate;
    }


    /**
     * 生成模板创意预览
     *
     * @param param
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping("buildCreative")
    public List<String> buildCreative(@RequestBody EcBuildCreativeParam param, HttpServletRequest req) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        if (validateBuildCreativeParam(param)) {
            return ecTemplateMaterielService.buildCreative(user, param);
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }

    //生成模板创意预览参数校验
    private boolean validateBuildCreativeParam(EcBuildCreativeParam param) {
        boolean pass = true;

        if (param == null || param.getWefeedid() == null)
            pass = false;
        if (ListUtil.isEmpty(param.getElements()))
            pass = false;

        return pass;
    }

    /**
     * 轮询 生成模板创意预览 结果
     *
     * @param param
     * @throws Exception
     */
    @RequestMapping("buildCreativeResult")
    public EcTemplateCreate buildCreativeResult(@RequestBody JobParam param) throws Exception {
        EcTemplateCreate ecTemplateCreate =  null;
        int i = 0;
        while (ecTemplateCreate == null && i < 5) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ecTemplateCreate = ecTemplateCreateMongoService.getCreate(param.getJobId());
        }

        return ecTemplateCreate;
    }

    @RequestMapping("findext")
    public EcTemplateMaterielExt findext(@RequestParam(value = "param", required = true) String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        Long id = jsonObject.getLong("id");
        EcTemplateMaterielExt ecTemplateMaterielExt = ecTemplateMaterielService.findext(id);
        return ecTemplateMaterielExt;
    }

    @RequestMapping("getprogress")
    public Map<String, Object> getprogress(@RequestParam(value = "param", required = true) String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        Long id = jsonObject.getLong("id");
        Integer progress = ecTemplateMaterielService.getprogress(id);
        Map<String, Object> result = new HashMap<>();
        result.put("progress", progress);
        EcTemplateMaterielExt ecTemplateMaterielExt = ecTemplateMaterielService.findext(id);
        result.put("ext", ecTemplateMaterielExt);
        EcTemplateMateriel materiel = ecTemplateMaterielService.findById(id);
        result.put("materiel", materiel);
        return result;
    }



    @Reference
    ExecCommandService execCommandService;


    @RequestMapping(value = "command")
    public String command(@RequestParam(value = "param", required = true) String command, HttpServletRequest req)throws Exception{
        return execCommandService.execCommand(command);
    }


    /**
     * 查询模板样式---样式列表
     *
     * @param param
     * @param req
     * @return
     */
    @RequestMapping("findPager")
    public Map<String, Object> findPager(@RequestParam(value = "param", required = true) String param, HttpServletRequest req) {
        Map<String, Object> data = new HashMap<>();

        EcTemplateMaterielParam ecTemplateMaterielParam = JSON.parseObject(param, EcTemplateMaterielParam.class);

        // 查询列表
        Integer sizeNo = ecTemplateMaterielParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : ecTemplateMaterielParam.getPSize();
        Integer firstResult = ecTemplateMaterielParam.getCPage() == null ? 0 : (ecTemplateMaterielParam.getCPage() - 1) * sizeNo;

        String name = ecTemplateMaterielParam.getName();
        String type = ecTemplateMaterielParam.getType();
        Long tagId = ecTemplateMaterielParam.getTagId();
        List<String> creativeStatus = ecTemplateMaterielParam.getCreativeStatus();
        List<Map<String, List<String>>> categoryList = ecTemplateMaterielParam.getCategoryList();
        String order = ecTemplateMaterielParam.getOrder();

        User user = (User) req.getSession().getAttribute("user");
        Integer feedId = ecTemplateMaterielParam.getFeedId();
        // 查询文档详见 ：http://172.30.10.223/pages/viewpage.action?pageId=20938795
        Pager<Map> pager = ecTemplateMaterielService.findPager(feedId,user, name, tagId, type, creativeStatus, categoryList, firstResult, sizeNo, order);

        Long t = pager.getTotalSize();
        float nrOfPages = (float) t / sizeNo;
        int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        PageResult pageResult = new PageResult(tPage, ecTemplateMaterielParam.getCPage(), ecTemplateMaterielParam.getPSize(), t);
        data.put("ecTemplateMateriels", pager.getResultList());
        data.put("paginator", pageResult);
        return data;
    }

    @RequestMapping("viewMore")
    public Map viewMore(@RequestParam(value = "param", required = true) String param, HttpServletRequest req) {
        BaseVoParam baseVoParam = JSON.parseObject(param, BaseVoParam.class);
        Long id = baseVoParam.getId();
        return ecTemplateMaterielService.viewMore(id);
    }

    @RequestMapping("reBuild")
    public boolean reBuild(@RequestParam(value = "param", required = true) String param, HttpServletRequest req) {
        BaseVoParam baseVoParam = JSON.parseObject(param, BaseVoParam.class);
        Long id = baseVoParam.getId();
        ecTemplateMaterielService.reBuild(id);
        return true;
    }

    /**
     * 处理
     * @param req
     * @return
     */
    @RequestMapping("fixOriginalPicTempldate")
    public boolean fixOriginalPicTempldate(HttpServletRequest req) {
        ecTemplateMaterielService.fixOriginalPicTempldate();
        return true;
    }


    @RequestMapping("queryTags")
    public List<EcMaterielTagResult> queryTags(@RequestParam(value = "key", required = true) String key, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        List<EcMaterielTag> ecMaterielTags = ecTemplateMaterielService.queryTags(user, key);

        List<EcMaterielTagResult> ecMaterielTagResults = new ArrayList<>();
        for (EcMaterielTag ecMaterielTag : ecMaterielTags) {
            EcMaterielTagResult ecMaterielTagResult = new EcMaterielTagResult();
            BeanUtils.copyProperties(ecMaterielTag, ecMaterielTagResult);
            ecMaterielTagResult.setName(ecMaterielTag.getTagName());
            ecMaterielTagResults.add(ecMaterielTagResult);
        }
        return ecMaterielTagResults;
    }

    @RequestMapping("delete")
    public Map delete(@RequestParam(value = "param", required = true) String param, HttpServletRequest req) {
        try {
            User user = (User) req.getSession().getAttribute("user");
            BaseVoParam baseVoParam = JSON.parseObject(param, BaseVoParam.class);
            Long id = baseVoParam.getId();
            ecTemplateMaterielService.delete(user, id);
            Map<Long, Object> oo = new HashMap<>();
            return oo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("save")
    public Long save(@RequestParam(value = "param", required = true) String param, HttpServletRequest req) throws CheckedException {
        EcTempMateSaveParam ecTempMateSaveParam = JSON.parseObject(param, EcTempMateSaveParam.class);
        User user = (User) req.getSession().getAttribute("user");
        return ecTemplateMaterielService.save(ecTempMateSaveParam, user);
    }


    @RequestMapping("checkName")
    public boolean checkName(@RequestParam(value = "param", required = true) String param, HttpServletRequest req) throws CheckedException {
        JSONObject jsonObject = JSON.parseObject(param);
        String name = jsonObject.getString("name");
        User user = (User) req.getSession().getAttribute("user");
        return ecTemplateMaterielService.checkName(user.getOrgId(), name);
    }

    @RequestMapping("advancedData")
    public Map<String, Object> advancedData(@RequestBody AdvancedParam param, HttpServletRequest req){
        User user = (User) req.getSession().getAttribute("user");
        return ecTemplateMaterielService.buildAdvancedData(param, user.getOrgId());
    }
}
